//
//  AppPublic.m
//  SmartTeaching
//
//  Created by yangqingluo on 15/9/21.
//  Copyright © 2015年 yangqingluo. All rights reserved.
//

#import "AppPublic.h"
#import <CommonCrypto/CommonDigest.h>

@implementation QKUserData


@end

@interface AppPublic()<NSXMLParserDelegate>


@property (nonatomic, strong) NSXMLParser *xmlParser;

@end

@implementation AppPublic



__strong static AppPublic  *_singleManger = nil;

+(AppPublic *)shareInstanceApp
{
    static dispatch_once_t pred = 0;
    
    
    
    dispatch_once(&pred, ^{
        _singleManger = [[AppPublic alloc]init];
        
        
    });
    return _singleManger;
}

-(instancetype)init{
    if (_singleManger) {
        return _singleManger;
    }
    
    self = [super init];
    
    if (self) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            self.showMapView = [[MKMapView alloc]init];
            //        self.showMapView.showsUserLocation = YES;
            //
            //        if ([CLLocationManager locationServicesEnabled]//确定用户的位置服务启用
            //            &&   [CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorized)//位置服务是在设置中禁用
            //        {
            //            
            //        }
        });
        
        
    }
    
    return self;
}

NSDate *dateFromString(NSString *dateString){
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    [dateFormatter setDateFormat: @"yyyy-MM-dd HH:mm:ss"];
    
    NSDate *destDate= [dateFormatter dateFromString:dateString];
    
    
    return destDate;
    
}

NSString *stringFromDate(NSDate *date){
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSString *destDateString = [dateFormatter stringFromDate:date];
    
    
    return destDateString;
}

NSString *stringFromDateInHHmmss(NSDate *date){
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    [dateFormatter setDateFormat:@"HH:mm:ss"];
    
    NSString *destDateString = [dateFormatter stringFromDate:date];
    
    
    return destDateString;
}

NSDate *birthdayFromString(NSString *dateString){
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    [dateFormatter setDateFormat: @"yyyy/MM/dd"];
    
    NSDate *destDate= [dateFormatter dateFromString:dateString];
    
    
    return destDate;
    
}
NSString *stringFromBirthday(NSDate *date){
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    [dateFormatter setDateFormat:@"yyyy/MM/dd"];
    
    NSString *destDateString = [dateFormatter stringFromDate:date];
    
    
    return destDateString;
}

NSString *stringFromNextDay(NSDate *date){
    NSDate *nextDay = [date dateByAddingTimeInterval:24 * 60 * 60];
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    [dateFormatter setDateFormat:@"yyyy/MM/dd"];
    
    NSString *destDateString = [dateFormatter stringFromDate:nextDay];
    
    
    return destDateString;
}


NSString *httpRespString(NSError *error, NSObject *object){
    if (error) {
        return @"网络出错";
    }
    NSString *noticeString = @"出错";
    
    if ([object isKindOfClass:[NSDictionary class]]) {
        if ([(NSDictionary *)object objectForKey:@"msg"]) {
            noticeString = [(NSDictionary *)object objectForKey:@"msg"];
        }
    }
    
    return noticeString;
}

NSString *starMiddle(NSString *string){
    if (string.length == kPhoneNumberLength) {
        NSMutableString *starString = [NSMutableString stringWithString:string];
        [starString replaceCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
        
        return [NSString stringWithString:starString];
    }
    
    
    return string;
}

NSString *sha1(NSString *string){
    const char *cstr = [string cStringUsingEncoding:NSUTF8StringEncoding];
    
    NSData *data = [NSData dataWithBytes:cstr length:string.length];
    
    uint8_t digest[CC_SHA1_DIGEST_LENGTH];
    
    
    
    CC_SHA1(data.bytes, (unsigned int)data.length, digest);
    
    
    
    NSMutableString *outputStr = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
    
    
    
    for(int i=0; i < CC_SHA1_DIGEST_LENGTH; i++) {
        
        [outputStr appendFormat:@"%02x", digest[i]];
        
    }
    
    return outputStr;
    
//    const char *cstr = [srcString cStringUsingEncoding:NSUTF8StringEncoding];
//    NSData *data = [NSData dataWithBytes:cstr length:srcString.length];
//    
//    uint8_t digest[CC_SHA1_DIGEST_LENGTH];
//    
//    CC_SHA1(data.bytes, data.length, digest);
//    
//    NSMutableString* result = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
//    
//    for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++) {
//        [result appendFormat:@"%02x", digest[i]];
//    }
//    
//    return result;
}

//检查该版本是否第一次使用
BOOL isFirstUsing(){
    //此为找到plist文件中得版本号所对应的键
    
    NSString *key = @"CFBundleShortVersionString";
    
    // 1.从plist中取出版本号
    
    NSString *version = [NSBundle mainBundle].infoDictionary[key];
    
    // 2.从沙盒中取出上次存储的版本号
    
    NSString *saveVersion = [[NSUserDefaults  standardUserDefaults] objectForKey:key];
    
    // 3.写入本次版本号
    [[NSUserDefaults  standardUserDefaults] setObject:version forKey:key];
    [[NSUserDefaults  standardUserDefaults] synchronize];
    
    
    return ![version isEqualToString:saveVersion];
}

- (QKUserData *)username_password{
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    if ([ud objectForKey:kUserName_Password]) {
        NSString *u_p = [ud objectForKey:kUserName_Password];
        NSArray *array = [u_p componentsSeparatedByString:@"&"];
        QKUserData *userdata = [QKUserData new];
        userdata.username = array[0];
        userdata.password = array[1];
        
        return userdata;
    }
    
    return nil;
}

- (void)clearUserData{
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    [ud removeObjectForKey:kUserName_Password];
    
    self.Token = nil;
}

- (void)saveUserData:(NSString *)username password:(NSString *)password{
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    [ud setObject:[NSString stringWithFormat:@"%@&%@",username,password] forKey:kUserName_Password];
}

- (void)adjustNavBar{
    [[UINavigationBar appearance] setBarStyle:UIBarStyleBlackOpaque];
    [[UINavigationBar appearance] setTitleTextAttributes:
     [NSDictionary dictionaryWithObjectsAndKeys:RGBA(245, 245, 245, 1), NSForegroundColorAttributeName, [UIFont fontWithName:@"HelveticaNeue-CondensedBlack" size:20.0], NSFontAttributeName, nil]];
}

- (void)clearMapView{
//    self.showMapView.delegate = nil;
    
    if (self.showMapView.annotations) {
        [self.showMapView removeAnnotations:self.showMapView.annotations];
    }
    
    if (self.showMapView.overlays) {
        [self.showMapView removeOverlays:self.showMapView.overlays];
    }
}

- (void)presentLoginVC:(UIViewController *)sourceVC{
    [sourceVC presentViewController:[[UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]] instantiateViewControllerWithIdentifier:@"LoginNavVC"] animated:YES completion:^{
        
    }];
}


+(void)doLogin{
    [[NSNotificationCenter defaultCenter] postNotificationName:kAppDelegateFunction object:@FUN_LOGIN];
}
+(void)doLogout{
    [[NSNotificationCenter defaultCenter] postNotificationName:kAppDelegateFunction object:@FUN_LOGOUT];
}


+(NSString *)filePath:(NSString *)folderName fileName:(NSString *)file
{
    NSString * rootPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString * rootFolder = [rootPath stringByAppendingPathComponent:kRootFolder];
    NSFileManager * fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:rootFolder]) {
        [fileManager createDirectoryAtPath:rootFolder withIntermediateDirectories:NO attributes:nil error:nil];
    }
    
    NSString * fileFolder = [rootFolder stringByAppendingPathComponent:folderName];
    if (![fileManager fileExistsAtPath:fileFolder]) {
        [fileManager createDirectoryAtPath:fileFolder withIntermediateDirectories:NO attributes:nil error:nil];
    }
    return [fileFolder stringByAppendingPathComponent:file];
}

+(NSString *)circleFilePath{
    return [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"circle"];
}

+(NSString *)imgFilePath{
    return [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"img"];
}

- (void)setPush:(BOOL)isPush{
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    [ud setObject:[NSNumber numberWithBool:isPush] forKey:kPush];
}
- (BOOL)queryPush{
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    return [[ud objectForKey:kPush] boolValue];
}


- (void)parseWithString:(NSString *)string{
    self.parseDic = [NSMutableDictionary new];
    
    self.xmlParser = [[NSXMLParser alloc]initWithData:[string dataUsingEncoding:NSUTF8StringEncoding]];
    [self.xmlParser setDelegate: self];
    [self.xmlParser setShouldResolveExternalEntities: YES];
    [self.xmlParser parse];
}

#pragma mark
#pragma NSXMLParserDelegate
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *) namespaceURI qualifiedName:(NSString *)qName attributes: (NSDictionary *)attributeDict{
    
    NSLog(@"4 parser didStarElemen:%@ namespaceURI:%@ qualifiedName:%@ attributes:%@",elementName,namespaceURI,qName,attributeDict);
    
    if (attributeDict) {
        if (attributeDict[@"value"] && attributeDict[@"name"]) {
            [self.parseDic setObject:attributeDict[@"value"] forKey:attributeDict[@"name"]];
        }
    }
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
    NSLog(@"5 parser: foundCharacters:%@",string);
}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
    NSLog(@"6 parser didEndElemen:%@ namespaceURI:%@ qualifiedName:%@",elementName,namespaceURI,qName);
}
- (void)parserDidStartDocument:(NSXMLParser *)parser{
    NSLog(@"-------------------start--------------");
}

- (void)parserDidEndDocument:(NSXMLParser *)parser{
    NSLog(@"-------------------end--------------");
}
//报告不可恢复的解析错误
- (void)paser:parserErrorOccured{
    NSLog(@"-------------------error--------------");
}

@end

